package com.bstech.Utils;

import java.io.StringReader;
import javax.xml.parsers.DocumentBuilderFactory;
import org.acra.ErrorReporter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xmlpull.v1.XmlSerializer;

import android.util.Log;
import android.util.Xml;

public class XmlParser {
	public static NodeList ParseNodes(String xml, String nodeName) {
		Document doc;
		NodeList ret = null;

		StringReader sr = null;
		InputSource is = null;
		Element root = null;

		try {
			sr = new StringReader(xml);
			is = new InputSource(sr);

			doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
					.parse(is);
			root = doc.getDocumentElement();

			ret = root.getElementsByTagName(nodeName);

		} catch (Exception e) {
			Log.e("XmlParser.ParseNodes", "Errore durante il parse di un nodo "
					+ nodeName + " Errore: " + e.toString());
			ErrorReporter.getInstance().handleException(e);
		} finally {
			root = null;
			doc = null;
			is = null;
			if (sr != null)
				sr.close();
			sr = null;
		}

		return ret;
	}

	public static XmlSerializer CreateSerializer()
	{
		 return Xml.newSerializer();
	}
	public static void addTagAndValue(XmlSerializer serializer, String tag, String value) throws Exception 
	{
		serializer.startTag("", tag);
		serializer.text(value); // TODO qualche conversione??
		serializer.endTag("", tag);
	}
}
